/**
 * 设置商户银行卡信息接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	if(postData.bankCardRealName && postData.bankCardNumber) {
		db.select('storeInfo').then(function(storeInfo) {
			if(storeInfo.length > 0) {
				for(let infoIndex in storeInfo) {
					if(storeInfo[infoIndex].storeBankCardInfo) {
						db.update('storeInfo', {
							_id: storeInfo[infoIndex]._id
						}, {
							storeBankCardInfo: {
								bankCardRealName: postData.bankCardRealName,
								bankCardNumber: postData.bankCardNumber
							}
						}).then(function() {
							deferred.resolve(1);
						}, function() {
							//设置商户银行卡信息失败
							deferred.reject('-0216');
						})
						break;
					}
					if(infoIndex == storeInfo.length - 1) {
						db.insert('storeInfo', {
							storeBankCardInfo: {
								bankCardRealName: postData.bankCardRealName,
								bankCardNumber: postData.bankCardNumber
							}
						}).then(function() {
							deferred.resolve(1);
						}, function() {
							//设置商户银行卡信息失败
							deferred.reject('-0216');
						});
					}
				}		
			}
			else {
				//查询商户信息失败
				deferred.reject('-0040');
			}
		}, function() {
			//查询商户信息失败
			deferred.reject('-0040');
		});
	}
	else {
		//设置商户银行卡信息接口数据不足
		deferred.reject('-0215');
	}
	return deferred.promise;
}

module.exports = {
	index: index
}